<?php

namespace Cck\ArticlesSystem\Http\Controllers;

use Cck\ArticlesSystem\Http\Resources\SettingResource;
use Cck\ArticlesSystem\Http\Models\Setting;
use Cck\ArticlesSystem\Http\Requests\SettingStoreRequest;
use Cck\ArticlesSystem\Http\Requests\SettingUpdateRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class SettingsController extends Controller
{
    public function all()
    {
        return SettingResource::collection(
            Setting::query()->with($this->getWith())->get()
        );
    }

    /**
     * 创建设置
     *
     * @param SettingStoreRequest $request
     * @return void
     */
    public function store(SettingStoreRequest $request)
    {
        return new SettingResource(
            Setting::query()->create($request->validated())
        );
    }

    public function update(Setting $setting, SettingUpdateRequest $request)
    {
        $setting->update($request->validated());

        return ['status' => true];
    }

    public function batchUpdate(Request $request)
    {
        $settings = $request->input('settings', []);

        DB::beginTransaction();

        try {
            foreach ($settings as $setting) {
                DB::table('settings')->where('id', $setting['id'])->update([
                    'value' => $setting['value']
                ]);
            }

            DB::commit();

            return ['status' => true];
        } catch (\Throwable $e) {
            DB::rollback();

            return ['status' => false, 'message' => $e->getMessage()];
        }
    }

    public function show(Setting $setting)
    {
        $setting->load($this->getWith());
        return new SettingResource($setting);
    }

    public function destroy(Request $request)
    {
        $ids = $request->input('ids', []);

        if (!is_array($ids)) {
            return ['status' => false, 'message' => '请传递要删除的ID数组'];
        }

        $ids = array_filter(array_unique(array_map('intval', $ids)));

        if (!count($ids)) {
            return ['status' => false, 'message' => '请传递要删除的ID数组'];
        }

        \DB::beginTransaction();

        $count = Setting::query()->whereIn('id', $ids)->delete();

        if (count($ids) !== $count) {
            \DB::rollBack();

            return ['status' => false, 'message' => '删除失败'];
        }

        \DB::commit();

        return ['status' => true];
    }
}
